<template>
  <view class="confirm-order">
      <!-- 地址 -->
      <view class="oder-map" @click="goToAddressPage">
        <template v-if="selectedAddress">
          <view class="map-title">
            <view class="map-name">收件人：{{selectedAddress.name}}</view>
            <view>{{selectedAddress.phone}}</view>
          </view>
          <view>收货地址：{{selectedAddress.province}}{{selectedAddress.city}}{{selectedAddress.town}}{{selectedAddress.address}}</view>
        </template>
        <!-- 如果没有选中的地址 -->
        <template v-else>
          <view class="map-title">
            <view class="map-name">请选择地址</view>
          </view>
        </template>
      </view>
    <!-- 商品 -->
    <view class="goods-list">
      <label class="radio foot-radio" @click="toggleSelectAll">
        <radio value="all" color="#FF3333" :checked="checkedAll"/><text>全选</text>
      </label>
      <view class="goods-item" v-for="(carts, index) in cartslist" :key="index">
        <label class="radio" @click="handleItemSelection(carts)">
          <radio value="" color="#FF3333" :checked="carts.checked"/><text></text>
        </label>
        <image class="goods-img" :src="carts.images"></image>
        <view class="goods-text">
          <view class="goods-name">{{carts.goodsName}}</view>
          <view class="goods-size">{{carts.description}}</view>
          <view class="goods-price">
            <view>￥{{carts.price}}</view>
          </view>
		  <view class='price-actions'>
		           <QuantityControl
		             :value="carts.quantity"
		             @quantity-updated="updateCartQuantity(carts.cartid, $event)"
		           />
		  </view>
        </view>
      </view>
    </view>
    <!-- 底部：提交订单 -->
    <view class="order-foot">
      <view class="foot-total">
        <view class="foot-count">合计：
		<text class="foot-count">￥{{ calculateTotalPrice }}</text>
		</view>
        <view class="foot-num" @click="submitOrder" style="background-color: #f0f0f0; color: #7acfa6; padding: 15rpx 35rpx; font-size: 32rpx;">提交订单</view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/config';
import QuantityControl from './QuantityControl.vue';
export default {
	components: {
	  QuantityControl
	},
   data() {
      return {
        defaultAddress: null, // 用于存储默认地址数据
        cartslist: [], // 用于存储商品数据
        checkedAll: false,
		selectedAddress: null
      };
    },
  computed: {
     // 计算选中商品的总价
    calculateTotalPrice() {
      return this.cartslist.reduce((total, item) => {
        if (item.checked) {
          // 确保价格和数量都是有效的数字
          const price = parseFloat(item.price);
          const quantity = parseInt(item.quantity, 10);
          if (!isNaN(price) && !isNaN(quantity)) {
            return total + (price * quantity);
          }
        }
        return total;
      }, 0).toFixed(2); // 保留两位小数
    }

    },
  mounted() {
    this.getDefaultAddress(); // 页面加载时调用获取默认地址的方法
    this.getSelectedCarts(); // 页面加载时调用获取选择的商品数据的方法
  },
  created() {
    // 监听自定义事件
    uni.$on('selectAddress', (address) => {
      this.selectedAddress = address; // 更新选中的地址数据
    });
  },
  methods: {
	 //更新商品数量
	 	updateCartQuantity(cartId, newQuantity) {
	 	        // Update the quantity of the item in the cart
	 	        const item = this.cartslist.find(cart => cart.cartid === cartId);
	 	        if (item) {
	 	          item.quantity = newQuantity;
	 	          this.calculateTotalPrice();
	 	        }
	 	},
		calculateTotalPrice() {
		    return this.cartslist.reduce((total, item) => {
		      if (item.checked) {
		        // 确保价格和数量都是有效的数字
		        const price = parseFloat(item.price);
		        const quantity = parseInt(item.quantity, 10);
		        if (!isNaN(price) && !isNaN(quantity)) {
		          return total + (price * quantity);
		        }
		      }
		      return total;
		    }, 0).toFixed(2); // 保留两位小数
		  },
		  
     goToAddressPage() {
      // 跳转到地址列表页面的方法
      uni.navigateTo({
        url: '/pages/mine/address/index2'
      });
    },
   

	
    handleItemSelection(item) {
      item.checked = !item.checked; // 切换选中状态
    },
    toggleSelectAll() {
      this.checkedAll = !this.checkedAll; // 切换全选按钮状态
      // 更新每个商品的选中状态
      this.cartslist.forEach((item) => {
        item.checked = this.checkedAll;
      });
    },
    getSelectedCarts() {
      // 从本地存储中获取选择的商品数据
      const selectedCarts = uni.getStorageSync('selectedCarts');
      if (selectedCarts) {
        this.cartslist = selectedCarts.cartslist;
      }
    },
   getDefaultAddress() {
     uni.request({
       url: config.apiUrl + '/address/getdefaultaddress',
       method: 'GET',
       success: (res) => {
         console.log("API Response:", res.data); // 调试信息
         if (res.statusCode === 200) {
           this.defaultAddress = res.data; // 存储默认地址
           this.selectedAddress = res.data; // 设置 selectedAddress 的初始值为默认地址
         } else {
           console.error('Failed to fetch default address:', res);
         }
       },
       fail: (err) => {
         console.error('Request failed:', err);
       }
     });
   },
submitOrder() {
  // 获取选中的商品
  const selectedItems = this.cartslist.filter(item => item.checked);

  // 如果没有选中的商品，提示用户
  if (selectedItems.length === 0) {
    uni.showToast({
      title: '请至少选择一个商品',
      icon: 'none'
    });
    return;
  }

  // 创建订单对象数组
  const orders = selectedItems.map(item => ({
    orderCount: item.quantity || '1', // 如果商品没有 count 属性，默认为 1
    remark: '', // 可以填写备注
    orderState: '0', // 设置初始状态为 0
    orderPrice: item.price,
    userId: this.defaultAddress ? this.defaultAddress.userId : null, // 从地址中获取用户 ID

    orderName: item.goodsName ,// 假设商品名称作为订单名称
	images:item.images,
	nickName:this.defaultAddress? this.defaultAddress.nickName : null, //从地址中获取用户昵称 
	shopId: item.shopId,
  }));

  // 计算总价并存储
  const totalPrice = this.calculateTotalPrice;
  uni.setStorageSync('totalPrice', totalPrice);

  // 发送请求到后端 API
  uni.request({
    url: config.apiUrl + '/order/create',
    method: 'POST',
    data: orders,
    header: {
      'Content-Type': 'application/json'
    },
    success: (res) => {
      if (res.statusCode === 200) {
        const createdOrders = res.data; // 这里是从后端返回的订单数据
        console.log("Created Orders: ", createdOrders);
        
        // 处理创建成功的订单数据
        // 例如，跳转到支付页面，并传递订单数据
        const orderId = createdOrders.map(order => order.orderId); // 假设你可以从每个订单中获取 ID
        uni.setStorageSync('orderIds', orderId); // 存储订单 ID
        uni.navigateTo({
          url: `/pages/pay/goodspayment?orderIds=${orderId.join(',')}`
        });
      } else {
        uni.showToast({
          title: '提交订单失败',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('Request failed:', err);
      uni.showToast({
        title: '请求失败',
        icon: 'none'
      });
    }
  });
}
  }
};
</script>

<style scoped>
.confirm-order {
  position: relative;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: #f7f7f7;
}
.oder-map {
  padding: 20rpx;
  background-color: #ffffff;
  line-height: 40rpx;
}
.map-title {
  display: flex;
  justify-content: space-between;
}
.map-name {
  font-weight: bold;
}
.goods-list {
  margin-top: 20rpx;
  background-color: #ffffff;
  padding: 20rpx 0;
}
.goods-item {
  margin-top: 20rpx;
  padding: 10rpx 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f7f7f7;
}
.goods-text {
  width: 360rpx;
  padding: 0 10rpx;
  font-size: 26rpx;
}
.goods-img {
  width: 160rpx;
  height: 160rpx;
}
.goods-name {
  font-size: 26rpx;
}
.order-foot {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  background-color: #ffffff;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.total-price {
  padding: 0 20rpx;
}
.price-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
